package cz.acies.genea.data.gedcom.tools;

import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import org.xml.sax.SAXParseException;

import cz.acies.genea.data.gedcom.model.Gedcom;
import cz.acies.genea.data.gedcom.model.GedcomTag;
import cz.acies.genea.data.gedcom.parser.JsonParser;
import cz.acies.genea.data.gedcom.parser.ModelParser;
import cz.acies.genea.data.gedcom.parser.TreeParser;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class Gedcom2Json
{
	//@Option(name = "-i", required = true, usage = "gedcom file in")
	private File gedcomIn = new File("./data/data.ged");

	//@Option(name = "-o", required = false, usage = "json file out")
	private File jsonOut = new File("./data/data.json");

	//@Option(name = "-t", required = false, usage = "use tree parser (use model parser by default)")
	private boolean useTreeParser = true;

	private void doMain() throws SAXParseException, IOException {
		String json;
		JsonParser jsonParser = new JsonParser();
		if (useTreeParser) {
			TreeParser treeParser = new TreeParser();
			List<GedcomTag> gedcomTags = treeParser.parseGedcom(gedcomIn);
			json = jsonParser.toJson(gedcomTags);
		} else {
			ModelParser modelParser = new ModelParser();
			Gedcom gedcom = modelParser.parseGedcom(gedcomIn);
			json = jsonParser.toJson(gedcom);
		}
		if (jsonOut != null) {
			PrintWriter writer = new PrintWriter(jsonOut);
			writer.println(json);
			writer.close();
		} else {
			System.out.println(json);
		}
	}

	public static void main(String[] args) throws SAXParseException, IOException {
		Gedcom2Json self = new Gedcom2Json();
		CmdLineParser parser = new CmdLineParser(self);
		try {
			parser.parseArgument(args);
			self.doMain();
		} catch (CmdLineException e) {
			System.err.println(e.getMessage());
			//parser.printUsage(System.err);
		}
	}
}
